package com.ostrich.library_logger.logger

import android.util.Log
import com.blankj.utilcode.util.CacheDiskStaticUtils
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.TimeUtils
import com.ostrich.library_logger.LoggerLevel
import java.io.File
import java.io.FileOutputStream

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/20 10:22
 * @Description : FileLogger:输出在本地文件中
 */
class FileLogger: ILogger {
    private var isDebug: Boolean = true
    private var tag:String = ""
    private var level: LoggerLevel = LoggerLevel.Debug
    private var url: String = ""
    private var loggerFormat = "%s (:============>$tag %s ----->%s)" //格式化字符串  %s代表占位符
    override fun d(tag: String, log: String) {
        if(isDebug && level.ordinal >= LoggerLevel.Debug.ordinal){
            //将日志写到文件中
            val nowString = TimeUtils.getNowString()
            //原生
            if(!File(url).exists()){
                File(url).createNewFile()
            }

            var fileOutputStream:FileOutputStream? = FileOutputStream(File(url),true)//追加
            try {
                fileOutputStream?.write(String.format(loggerFormat,nowString,tag,log).toByteArray())
                fileOutputStream?.write("\n".toByteArray())
            }catch (e:Exception){
                e.printStackTrace()
            }finally {
                if(fileOutputStream != null){
                    fileOutputStream.close()
                    fileOutputStream = null
                }
            }




        }

    }

    override fun v(tag: String, log: String) {

    }

    override fun i(tag: String, log: String) {

    }

    override fun w(tag: String, log: String) {

    }

    override fun e(tag: String, log: String) {

    }

    override fun setDebug(isDebug: Boolean) {
        this.isDebug = isDebug
    }

    override fun setLogTag(TAG: String) {
        this.tag = TAG
    }

    override fun setLoggerLevel(level: LoggerLevel) {
        this.level = level
    }

    override fun setSaveUrl(url: String) {
        this.url = url
    }
}